//
//  PhotoViewAnimation.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/21.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit

class PhotoViewAnimation: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
    // 是否正在转场
    var isPresent = false
    
    // 负责消失
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        return self
    }
    
    // 负责呈现
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        return self
    }
    
    // 动画时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 1.0
    }
    
    
    // 提供转场的细节
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 在转场
        if isPresent {
            // 转到目标控制器了
            if let toView = transitionContext.viewForKey(UITransitionContextToViewKey) {
                
                // 将目标视图添加到容器视图中
                transitionContext.containerView().addSubview(toView)
                
                toView.alpha = 0
                toView.frame = CGRectMake(0, 0, 0, 0)
                UIView.animateWithDuration(transitionDuration( transitionContext),
                    animations: { () -> Void in
                        toView.frame = UIScreen.mainScreen().bounds
                        toView.alpha = 1.0
                    }, completion: { (_) -> Void in
                        transitionContext.completeTransition(true)
                })
                
            }
        
        }
        // 处理由 presenting 跳转到 presented 控制器(结束转场)
        else {
            
            transitionContext.completeTransition(true)
        }
    }
    
}
